/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.munif.util;

import java.io.Serializable;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 *
 * @author André
 */
public class ConverterAutoComplete implements Converter, Serializable {

    private Class classe;

    public ConverterAutoComplete(Class classe) {
        this.classe = classe;
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {

        try {
            Object chave = Persistencia.getFieldId(classe).getType().getConstructor(String.class).newInstance(value);
            return CrudFacade.getInstance().recuperar(classe, chave);
        } catch (Exception ex) {
            //Evita mensagens durante a digitaçao parcial.
            //logger.log(Level.SEVERE, "Problema ao instanciar a chave", ex);
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {

        if (value != null) {
            return String.valueOf(value);
        } else {
            return null;
        }
    }
}
